package com.huangjue.backend.controller;


import com.huangjue.backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class UploadController {

    @Autowired
    private UserService userService;

    @Value("${upload.dir:uploads\\touxiang}")
    private String uploadDir;
    public void handleFileUpload(MultipartFile file) {
        // 处理文件上传逻辑
        System.out.println("Upload successful");
    }

    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Integer userId= Integer.valueOf(request.getParameter("userId"));
        Map<String, Object> response = new HashMap<>();
        if (file.isEmpty()) {
            response.put("success", false);
            response.put("message", "文件为空");
            return ResponseEntity.badRequest().body(response);
        }
        // 只允许图片
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            response.put("success", false);
            response.put("message", "只允许上传图片文件");
            return ResponseEntity.badRequest().body(response);
        }
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String ext = StringUtils.getFilenameExtension(originalFilename);
        String filename = UUID.randomUUID().toString().replaceAll("-", "") + (ext != null ? "." + ext : "");
        // 用绝对路径，确保在项目根目录下
        String realPath = new File("").getAbsolutePath()+"\\huangjuelan_frontend_back\\houduan\\online-course-system" + File.separator + uploadDir;
        System.out.println("realPath"+realPath);
        File dir = new File(realPath);
        if (!dir.exists()) dir.mkdirs();
        File dest = new File(dir, filename);
        try {
            file.transferTo(dest);
            String url = "/uploads/touxiang/" + filename;
            response.put("success", true);
            response.put("url", url);
            userService.changePicture(userId,url);
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "上传失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
} 